<template>
  <Layout>
    <div>
      <Card dis-hover>
        <h3>
          {{ taskInfo.taskName }}
        </h3>
        <ButtonGroup slot="extra" v-if="!taskInfo.viewFlag">
          <Button @click="submitAndUpdate('showdata')" type="warning" style="background: #EF5350;"
                  :loading="buttonloading1" v-if="taskInfo.procinstState === '2'">
            <Icon type="ios-bookmark"/>
            审批
          </Button>
          <Button @click="submit('showdata')" type="warning" style="background: #EF5350;" :loading="buttonloading1"
                  v-else>
            <Icon type="ios-bookmark"/>
            审批
          </Button>
          <Button @click="returnTo">
            返回
            <Icon type="ios-arrow-forward"/>
          </Button>
        </ButtonGroup>
        <ButtonGroup slot="extra" v-else>
          <Button @click="returnTo">
            返回
            <Icon type="ios-arrow-forward"/>
          </Button>
        </ButtonGroup>

      </Card>

      <div>
        <Card dis-hover style="margin-top: 10px">
          <div :style="{overflowY: 'auto'}" v-if="taskInfo.procinstState === '2'">
            <Col span="18">
              <Form :model="showdata" ref="showdata" :rules="ruleCustom1" :label-width="160">
                <Row type="flex" justify="space-around" class="code-row-bg">
                  <Col span="11">
                    <FormItem label="作业名称：" prop="serviceName">
                      <Input v-model="showdata.serviceName" readonly @on-focus="modelSearch=true"  suffix="ios-search"/>
                    </FormItem>
                  </Col>
                  <Col span="11">
                    <FormItem label="企业名称：" prop="contractorName">
                      <Input v-model="showdata.contractorName" readonly></Input>
                    </FormItem>
                  </Col>

                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                  <Col span='11'>
                    <FormItem label='联系人：' prop="contacts">
                      <Input v-model="showdata.contacts"/>
                    </FormItem>
                  </Col>
                  <Col span='11'>
                    <FormItem label='联系电话：' prop="phone">
                      <Input v-model="showdata.phone"/>
                    </FormItem>
                  </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                  <Col span="11">
                    <FormItem label='评价时间段：' prop="evaluationPeriodDate">
                      <Date-picker type="daterange" style="width: 100%" :clearable="false" v-model="evaluationPeriodDate"/>
                    </FormItem>
                  </Col>
                 <!-- <Col span="11">
                    <FormItem label='合同有效期：' prop="contractTermDate">
                      <Date-picker type="daterange" style="width: 100%" :clearable="false" v-model="contractTermDate"/>
                    </FormItem>
                  </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                  <Col span="11">
                    <FormItem label='供方资质：' prop="supplierQualification">
                      <Input v-model="showdata.supplierQualification"/>
                    </FormItem>
                  </Col> -->
                  <Col span="11">
                    <FormItem label="评价人：" prop="userName">
                      {{ showdata.userName }}
                    </FormItem>
                  </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                  <Col span="11">
                    <FormItem label="部门经理：" prop="departmentManagerUserName">
                      {{ showdata.departmentManagerUserName }}
                    </FormItem>
                  </Col>
                  <Col span="11">
                    <FormItem label="主管经理：" prop="executiveManagerUserName">
                      {{ showdata.executiveManagerUserName }}
                    </FormItem>
                  </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                  <Col span="11">
                    <FormItem label="公司经理：" prop="companyManagerUserName">
                      {{ showdata.companyManagerUserName }}
                    </FormItem>
                  </Col>
                  <Col span="11">
                    <FormItem label="评价等级：" prop="evaluationGrade">
                      {{ showdata.evaluationGrade }}
                    </FormItem>
                  </Col>
                </Row>

                <Row type="flex" justify="space-around" class="code-row-bg">
                  <Col span='23'>
                    <FormItem label='综合评价：' prop="comprehensiveEvaluation">
                      <Input v-model="showdata.comprehensiveEvaluation" type="textarea" :rows="5"
                             :autosize="{maxRows:5,minRows: 2}"/>
                    </FormItem>
                  </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                  <Col span="23">
                    <FormItem label="协议附件：">
                      <div>
                        <Upload ref="upload"
                                :before-upload="beforeUpload"
                                :show-upload-list="true"
                                :max-size="10240"
                                multiple
                                type="drag"
                                :action="fileUrl">
                          <div style="padding: 10px">
                            <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                            <p>点击将文件拖拽到这里上传</p>
                            <span style="font-size:8px;color: #797a64">支持扩展名：.rar .zip .doc .docx .pdf...</span>
                          </div>
                        </Upload>
                      </div>
                      <div v-show="uploadList.length>0" v-for="item in uploadList" :key='item'>
                        <a @click="downloadFile(showdata.perfId,item)">{{ item.fileName }}</a>
                        <Button type="text" icon="md-trash" @click="remove1(item.id)"
                                style="margin-left: 5px;margin-bottom: 3px"/>
                      </div>
                    </FormItem>
                  </Col>
                </Row>

              </Form>
              <Modal title="相关方作业信息" :transfer=false footer-hide v-model="modelSearch" :width=900>
                <working-related-parties v-if="modelSearch" v-show="modelSearch" :modelSearch="modelSearch"
                                         @getSelectModelData='danxuan' :companyId="showdata.companyId"></working-related-parties>
                <div slot="footer">
                  <Button class='ivu-btn-save' @click="onCancel">关闭</Button>
                </div>
              </Modal>
            </Col>
          </div>
          <div :style="{overflowY: 'auto'}" v-else>
            <Col span="24">
              <Form :model="showdata" ref="showdata" :rules="ruleCustom" :label-width="160">
                <Row type="flex" justify="space-around" class="code-row-bg">
                  <Col span="11">
                    <FormItem label="作业名称：" prop="serviceName">
                      {{ showdata.serviceName }}
                    </FormItem>
                  </Col>
                  <Col span="11">
                    <FormItem label="企业名称：" prop="contractorName">
                      {{ showdata.contractorName }}
                    </FormItem>
                  </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                  <Col span="11">
                    <FormItem label="联系人：" prop="staffName">
                      {{ showdata.contacts }}
                    </FormItem>
                  </Col>
                  <Col span="11">
                    <FormItem label="联系电话：" prop="auditorName">
                      {{ showdata.phone }}
                    </FormItem>
                  </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                  <Col span="11">
                    <FormItem label="评价时间段：" prop="approvedByName">
                      {{ evaluationPeriodDate1 }}
                    </FormItem>
                  </Col>
                  <!-- <Col span="11">
                    <FormItem label="合同有效期：" prop="whetherComments">
                      {{ contractTermDate1 }}
                    </FormItem>
                  </Col> -->
               <!-- </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                  <Col span="11">
                    <FormItem label="供方资质：" prop="reportingDate">
                      {{ showdata.supplierQualification }}
                    </FormItem>
                  </Col> -->
                  <Col span="11">
                    <FormItem label="评价人：" prop="userName">
                      {{ showdata.userName }}
                    </FormItem>
                  </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                  <Col span="11">
                    <FormItem label="部门经理：" prop="departmentManagerUserName">
                      {{ showdata.departmentManagerUserName }}
                    </FormItem>
                  </Col>
                  <Col span="11">
                    <FormItem label="主管经理：" prop="executiveManagerUserName">
                      {{ showdata.executiveManagerUserName }}
                    </FormItem>
                  </Col>
                </Row>
                <Row type="flex" justify="space-around" class="code-row-bg">
                  <Col span="11">
                    <FormItem label="公司经理：" prop="companyManagerUserName">
                      {{ showdata.companyManagerUserName }}
                    </FormItem>
                  </Col>
                  <Col span="11">

                  </Col>
                </Row>
                <!--                                <Row type="flex" justify="space-around" class="code-row-bg">-->
                <!--                                    <Col span="23">-->
                <!--                                        <FormItem label="管理状况：" prop="managementEvaluation">-->
                <!--                                            {{showdata.managementEvaluation}}-->
                <!--                                        </FormItem>-->
                <!--                                    </Col>-->
                <!--                                </Row>-->
                <!--                                <Row type="flex" justify="space-around" class="code-row-bg">-->
                <!--                                    <Col span="23">-->
                <!--                                        <FormItem label="履约能力：" prop="performanceEvaluation">-->
                <!--                                            {{showdata.performanceEvaluation}}-->
                <!--                                        </FormItem>-->
                <!--                                    </Col>-->
                <!--                                </Row>-->
                <!--                                <Row type="flex" justify="space-around" class="code-row-bg">-->
                <!--                                    <Col span="23">-->
                <!--                                        <FormItem label="售后评价：" prop="afterSaleEvaluation">-->
                <!--                                            {{showdata.afterSaleEvaluation}}-->
                <!--                                        </FormItem>-->
                <!--                                    </Col>-->
                <!--                                </Row>-->
                <Row type="flex" justify="space-around" class="code-row-bg">
                  <Col span="23">
                    <FormItem label="综合评价：" prop="comprehensiveEvaluation">
                      {{ showdata.comprehensiveEvaluation }}
                    </FormItem>
                  </Col>
                </Row>

                <Row type="flex" justify="space-around" class="code-row-bg">
                  <Col span="23">
                    <FormItem label="协议附件：">
                      <div v-show="uploadList.length>0" v-for="item in uploadList" :key='item'>
                        <a @click="downloadFile(showdata.perfId,item)">{{ item.fileName }}</a>
                      </div>
                    </FormItem>
                  </Col>
                </Row>
                <Row v-if="flag">
                  <Col span="11">
                    <FormItem label="审批结果：" prop="route">
                      <Select v-model="showdata.route" @on-change="routePush">
                        <Option v-for="item in approveList" :value="item.text" :key="item.text">{{
                            item.value
                          }}
                        </Option>
                      </Select>
                    </FormItem>
                  </Col>

                </Row>
                <Row v-if="flag">
                  <Col span="11">
                    <FormItem label="处理意见：" prop="opinion">
                      <Input v-model="showdata.opinion" type="textarea" :rows="2"/>
                    </FormItem>
                  </Col>
                </Row>

              </Form>
            </Col>
          </div>
        </Card>
      </div>
    </div>

  </Layout>
</template>


<script>
import {Api} from '../../../api/index.js'
import {sessionStorage} from '../../../common/cacheUtils.js'
import cascaderDom from "../../../components/cascader-dom.vue"
import workingRelatedParties from './workingRelatedParties.vue'

export default {
  components: {cascaderDom, workingRelatedParties},
  data() {
    return {
      model2:false,
      loading:false,
      taskInfo: {},
      user: {},
      fileUrl: Api.interestedPartiesUserFile,
      buttonloading1: false,
      evaluationPeriodDate: [null, null],
      contractTermDate: [null, null],
      uploadList: [],
      evaluationPeriodDate1: null,
      contractTermDate1: null,
      viewFlag: false,
      flag: false,
      approveFlag: '',
      approveList: [],
      showdata: {},
      tableHeight: 450,
      file: null,
      fileName: null,
      downloadUrl: Api.downloadMongoFile,
      formList: [],
      ruleCustom1: {
        serviceName: [{
          message: '  ',
          required: true,
          trigger: 'blue'
        }],
        contacts: [{
          message: '  ',
          required: true,
          trigger: 'blur'
        }],
        contractorName: [{
          message: '  ',
          required: true,
          trigger: 'change'
        }],

        phone: [{
          validator: (rule, value, callback) => {
            if (!(/^1[3456789]\d{9}$/.test(value))) {
              callback(' ');
              this.$Message.error("请填写有效的的手机号")
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'blur'
        }],
        evaluationPeriodDate: [{
          validator: (rule, value, callback) => {
            if (this.evaluationPeriodDate == null || this.evaluationPeriodDate[0] == null) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        managementEvaluation: [{
          message: '  ',
          required: true,
          trigger: 'blur'
        }],
        performanceEvaluation: [{
          message: '  ',
          required: true,
          trigger: 'blur'
        }],
        afterSaleEvaluation: [{
          message: '  ',
          required: true,
          trigger: 'blur'
        }],
        comprehensiveEvaluation: [{
          message: '  ',
          required: true,
          trigger: 'blur'
        }],
      },
      ruleCustom: {
        opinion: [
          {required: true, message: '  ', trigger: 'blur'}
        ],

        route: [
          {required: true, message: '  ', trigger: 'blur'}
        ]
      },
        modelSearch:false
    }
  },
  mounted: function () {
    if (this.$route.query.close == false) {
      this.$http.get(Api.getUserByUserId + this.$route.query.userId)
          .then(function (res) {
            this.user = res.data.data;
            this.$http.get(Api.getTaskData + "/" + this.$route.query.procinstId + "/" +
                this.$route.query.taskId + "?close=" + this.$route.query.close).then(function (res1) {
              this.taskInfo = res1.data;
              if (res1.data.viewFlag == false)
                this.taskInfo.viewFlag = false;
              else
                this.taskInfo.viewFlag = true;
              this.query();
              return;
            })
          })
    } else {
      var search = window.location.href.split('?')[1];//截取URL？后面的参数
      var params = {};
      if (search != "" && search != undefined) {
        search.split("&").forEach(
            function (val) {
              var arr = val.split("=");
              params[arr[0]] = arr[1];
            }
        )
      }
      var code = params.code
      var status = params.status
      if (code != null && code != 'undefine') {
        this.$http.get(Api.queryToken, {
          params: {
            code: code,
          }
        }).then(res1 => {
          if (res1.data.errcode == "1014") {
            this.$http.get(Api.getReZheng).then(res2 => {
              window.location.href = decodeURIComponent(res2.bodyText) + "&redirect_uri=" + encodeURIComponent(window.location.href);
            })
          } else {
            this.$http.get(Api.getUserByUserId + this.$route.query.userId)
                .then(function (res) {
                  this.user = res.data.data;
                  this.$http.get(Api.getTaskData + "/" + this.$route.query.procinstId + "/" +
                      this.$route.query.taskId + "?close=" + this.$route.query.close).then(function (res1) {
                    this.taskInfo = res1.data;
                    if (res1.data.viewFlag == false)
                      this.taskInfo.viewFlag = false;
                    else
                      this.taskInfo.viewFlag = true;
                    this.query();
                    return;
                  })
                })
          }
        })
      } else {
        this.$http.get(Api.getReZheng).then(res2 => {
          window.location.href = decodeURIComponent(res2.bodyText) + "&redirect_uri=" + encodeURIComponent(window.location.href);
        });
      }
    }
  },
  methods: {
    remove1(id) {
      console.log(id)
      let url = this.fileUrl + '/file/' + id;
      this.$http.delete(url).then((res) => {
        this.getFiles()
      })
    },
    returnTo() {
      if (this.taskInfo.close == true)
        window.close();
      else
        this.$router.go(-1);
    },
    routePush(value) {
      if (value === '1') {
        this.showdata.opinion = "同意";
      } else {
        this.showdata.opinion = null;
      }
    },
    beforeUpload(file) {
      console.log(this.uploadList)
      let formData = new FormData();
      formData.append("files", file); // 文件对象
      let url = this.fileUrl + '/' + this.showdata.perfId + '/files/agreementFile'
      this.$http.post(url, formData).then((res) => {
        if (res.data.result == "success") {
          this.$Message.info("文件上传成功")
          this.getFiles();
        }
      })
      return false
    },
    getFiles() {
      let url = this.fileUrl + '/' + this.showdata.perfId + '/files/agreementFile'
      this.$http.get(url).then((res) => {
        if (res.data.result == "success") {
          console.log(res.data)
          this.uploadList = res.data.data
        }
      })
    },
    setApproveUserName(data) {
      this.showdata.approveUserName = data;
    },
    setApproveUserId(data) {
      this.showdata.approveUserId = data[data.length - 1];
    },

    setApproveUserName1(data) {
      this.showdata.approveUserName = data;
    },
    setApproveUserId1(data) {
      let userId = "";
      for (let i = 0; i < data.length; i++) {
        userId += data[i]['value'] + ',';
      }
      this.showdata.approveUserId = userId;
    },
    downloadFile(perfId, file) {

      let url = Api.interestedPartiesUserFile + '/file/' + file.id;
      this.$http.get(url, {
        responseType: 'blob'      //告诉服务器我们需要的响应格式
      }).then((res) => {
        console.log(res)
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = file.fileName //标题
        aLink.click()
        document.body.appendChild(aLink)
      })
    },
    danxuan(row, index) {
      // this.showdata.contractorId = row.contractorId
      // this.showdata.contractorName = row.contractorName
      // this.model2 = false
        this.modelSearch = false;
        this.showdata.contractorName = row.relatedPartiesName//相关方名称
        this.showdata.serviceName = row.workingMatters//作业事项
        this.showdata.workingRelatedId = row.id//相关方作业id
    },

    query() {
      let url = Api.interestedPartiesEvaluatePref;
      let id = this.taskInfo.workId;

      this.$http.get(url + '/' + id, {params: {}}).then((res) => {
        this.showdata = res.data.data;
        this.getFiles();
        let contractTermStart = new Date(this.showdata.contractTermStart);
        contractTermStart = contractTermStart.getFullYear() + '-' + (contractTermStart.getMonth() + 1) + '-' + contractTermStart.getDate()
        let contractTermEnd = new Date(this.showdata.contractTermEnd);
        contractTermEnd = contractTermEnd.getFullYear() + '-' + (contractTermEnd.getMonth() + 1) + '-' + contractTermEnd.getDate()
        this.contractTermDate1 = contractTermStart + '至' + contractTermEnd
        this.contractTermDate = [contractTermStart, contractTermEnd];
        let evaluationPeriodStart = new Date(this.showdata.evaluationPeriodStart);
        evaluationPeriodStart = evaluationPeriodStart.getFullYear() + '-' + (evaluationPeriodStart.getMonth() + 1) + '-' + evaluationPeriodStart.getDate()
        let evaluationPeriodEnd = new Date(this.showdata.evaluationPeriodEnd);
        evaluationPeriodEnd = evaluationPeriodEnd.getFullYear() + '-' + (evaluationPeriodEnd.getMonth() + 1) + '-' + evaluationPeriodEnd.getDate()
        this.evaluationPeriodDate1 = evaluationPeriodStart + '至' + evaluationPeriodEnd
        this.evaluationPeriodDate = [evaluationPeriodStart, evaluationPeriodEnd]

        if (!this.viewFlag) {
          this.$http.get(Api.getProcinstForm + '/' + this.taskInfo.taskId, {params: {}}).then((res) => {
            console.log(res.data.formList)
            this.formList = res.data.formList;
            if (this.formList.length != 0) {
              if (this.formList[0].id == 'route') {
                this.flag = true;
                this.approveList = res.data.formList[0].enumData;
              }
            }
          }).catch(e => {
            this.$Message.error("数据获取失败")
            console.log(e);
          })
        }

      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    submitAndUpdate() {

      this.$refs['showdata'].validate((valid) => {
        console.log("xxx");
        console.log(valid);
        if (valid) {
          this.buttonloading1 = true;
          let data = {};
          data = {
            createUserId: this.user.userId,
            userName: this.user.userName,
            opinion: this.showdata.opinion,
            taskId: this.taskInfo.taskId,
            procinstId: this.taskInfo.procinstId,
            route: this.showdata.route
          };
          this.showdata.contractTermStart = this.contractTermDate[0]
          this.showdata.contractTermEnd = this.contractTermDate[1]
          this.showdata.evaluationPeriodStart = this.evaluationPeriodDate[0]
          this.showdata.evaluationPeriodEnd = this.evaluationPeriodDate[1]
          let url = Api.interestedPartiesEvaluatePrefUpdate;
          this.showdata.updateUserId = this.user.userId
          this.showdata.updateOrgId = this.user.orgInfo.orgId
          this.$http.post(url, this.showdata).then((res) => {
            if (res.data.status == '200') {
              data.route = '1';
              this.$http.get(Api.taskComplete, {params: data}).then((res) => {
                this.buttonloading1 = false;
                if (res.data.status == '200') {
                  this.$Message.success("审批成功")
                  this.returnTo();
                } else {
                  this.$Message.success("审批失败")
                }
              }).catch(e => {
                this.buttonloading1 = false;
                this.$Message.error("数据获取失败")
              })
            } else {
              this.buttonloading1 = false;
            }
          }).catch(e => {
            this.buttonloading1 = false;
            this.$Message.error('请求失败');

          })


        }
      })
    },
    submit() {
      this.$refs['showdata'].validate((valid) => {
        if (valid) {
          this.buttonloading1 = true;
          console.log('showdata');
          let data = {};
          data = {
            createUserId: this.user.userId,
            userName: this.user.userName,
            opinion: this.showdata.opinion,
            taskId: this.taskInfo.taskId,
            procinstId: this.taskInfo.procinstId,
            route: this.showdata.route
          };
          this.$http.get(Api.taskComplete, {params: data}).then((res) => {
            console.log(res)
            this.buttonloading1 = false;
            if (res.data.status == '200') {
              this.$Message.success("审批成功")
              this.returnTo();
            } else {
              this.$Message.success("审批失败")
            }
          }).catch(e => {
            this.buttonloading1 = false;
            this.$Message.error("数据获取失败")
          })


        } else {
          this.$Message.error('请填报完整!');
        }
      })
    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },
  },
}
</script>
<style lang='css' scoped>
@import '../../../index.css';

</style>
